package com.jiangyg.mall.db;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.core.config.GlobalConfig;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.extension.plugins.pagination.optimize.JsqlParserCountOptimize;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import com.jiangyg.mall.core.enums.Enable;
import com.jiangyg.mall.core.support.env.EnvConstant;
import com.jiangyg.mall.core.utils.Logger;
import com.jiangyg.mall.core.utils.springframework.ResourceUtils;
import com.jiangyg.mall.db.mybatis.SnowflakeIdGenerator;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.plugin.Interceptor;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.Resource;

import javax.sql.DataSource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 类描述：MyBatis配置
 *
 * @author jiangyg
 * @version 2.0
 * @date 2020-07-08
 */
@Slf4j
@Configuration
public class MyBatisAutoConfiguration extends MyBatisBaseConfigurer implements InitializingBean, BeanFactoryAware {

    /**
     * bean工厂
     */
    private BeanFactory beanFactory;

    /**
     * 功能描述：全局默认配置
     */
    public GlobalConfig globalConfig() {
        // 全局配置文件
        GlobalConfig globalConfig = new GlobalConfig();
        GlobalConfig.DbConfig dbConfig = new GlobalConfig.DbConfig();
        // 逻辑删除
        dbConfig.setLogicDeleteValue(Enable.N.scode);
        dbConfig.setLogicNotDeleteValue(Enable.Y.scode);
        // 默认为自增
        dbConfig.setIdType(IdType.AUTO);
        globalConfig.setDbConfig(dbConfig);
        // 自定义字段填充器
        if (beanFactory.containsBean(MyBatisConstant.META_OBJECT_HANDLER_NAME)) {
            final MetaObjectHandler metaObjectHandler = (MetaObjectHandler) beanFactory.getBean(MyBatisConstant.META_OBJECT_HANDLER_NAME);
            globalConfig.setMetaObjectHandler(metaObjectHandler);
        }
        // 不输出banber
        globalConfig.setBanner(false);
        // 自定义主键ID
        globalConfig.setIdentifierGenerator(new SnowflakeIdGenerator());
        return globalConfig;
    }

    /**
     * 功能描述：构建MybatisSqlSessionFactoryBean
     *
     * @param dataSource 数据源
     * @return MybatisSqlSessionFactoryBean
     * @throws IOException IO异常
     */
    @Primary
    @Bean(name = "sqlSessionFactory")
    public MybatisSqlSessionFactoryBean sqlSessionFactory(@Qualifier("dataSource") DataSource dataSource) throws IOException {
        final MybatisSqlSessionFactoryBean sqlSessionFactoryBean = new MybatisSqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        sqlSessionFactoryBean.setGlobalConfig(globalConfig());
        // 自动扫描 mapping.xml文件映射路径
        final String mapperLocations = EnvConstant.getString("spring.mybatis.mapperLocations");
        Logger.info(log, () -> String.format("[项目启动]-初始化MyBatis配置：自动扫描 mapping.xml文件映射路径[%s]", mapperLocations));
        final List<String> mapperLocationList = Collections.singletonList(mapperLocations);
        final Resource[] resources = ResourceUtils.obtainResourcesByPathMatching(mapperLocationList);
        sqlSessionFactoryBean.setMapperLocations(resources);
        // 源码里面如果有configuration, 不会注入BaseMapper里面的方法, 所以这里要这样写
        final MybatisConfiguration configuration = new MybatisConfiguration();
        configuration.setMapUnderscoreToCamelCase(true);
        sqlSessionFactoryBean.setConfiguration(configuration);
        // 设置分页插件
        final List<Interceptor> interceptors = new ArrayList<>();
        final PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
        paginationInterceptor.setCountSqlParser(new JsqlParserCountOptimize(true));
        // 设置插件
        interceptors.add(paginationInterceptor);
        sqlSessionFactoryBean.setPlugins(interceptors.toArray(new Interceptor[0]));
        return sqlSessionFactoryBean;
    }

    /**
     * 功能描述：自动扫描mapper映射路径
     *
     * @return MapperScannerConfigurer
     */
    @Primary
    @Bean(name = "mapperScannerConfigurer")
    public MapperScannerConfigurer mapperScannerConfigurer() {
        final String basePackage = EnvConstant.getString("spring.mybatis.basePackage");
        Logger.info(log, () -> String.format("[项目启动]-初始化MyBatis配置：自动扫描 mapper 映射路径[%s]", basePackage));
        return buildMapperScannerConfigurer(basePackage);
    }

    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        this.beanFactory = beanFactory;
    }

    @Override
    public void afterPropertiesSet() {
        Logger.info(log, () -> "初始化MyBatis配置……");
    }

}
